<script setup>
	import { ref } from 'vue'
	import PageContainer from '@/components/PageContainer.vue'
	import { useUserStore } from '@/stores'
	import { userInfoUpdateService } from '@/api/user'
	// 获取用户信息
	const {
		user: { id, username, nickname, email },
		getUser
	} = useUserStore()
	const userInfo = ref({
		id,
		username,
		nickname,
		email
	})

	const rules = ref({
		nickname: [
			{ required: true, message: '请输入昵称', trigger: 'blur' },
			{
				pattern: /^\S{2,10}$/,
				message: '2-10位非空字符串',
				trigger: 'blur'
			}
		],
		email: [
			{ required: true, message: '请输入邮箱', trigger: 'blur' },
			{
				type: 'email',
				message: '请输入有效的邮箱地址',
				trigger: 'blur'
			}
		]
	})
	//校验后封装调用
	const formRef = ref()
	const onSubmit = async () => {
		const valid = await formRef.value.validate()
		if (valid) {
			await userInfoUpdateService(userInfo.value)
			await getUser()
			// 提示
			ElMessage.success('修改成功')
		}
	}
</script>

<template>
	<PageContainer title="基本资料">
		<el-form
			:model="userInfo"
			:rules="rules"
			ref="formRef"
			label-width="100px"
			label-position="top"
			class="user-form"
		>
			<el-form-item label="登录名称" prop="username">
				<el-input v-model="userInfo.username" disabled />
			</el-form-item>

			<el-form-item label="用户昵称" prop="nickname">
				<el-input
					v-model="userInfo.nickname"
					placeholder="请输入2-10位昵称"
					clearable
				/>
			</el-form-item>

			<el-form-item label="用户邮箱" prop="email">
				<el-input
					v-model="userInfo.email"
					placeholder="请输入有效邮箱"
					clearable
				/>
			</el-form-item>

			<el-form-item>
				<el-button type="primary" @click="onSubmit"> 提交修改 </el-button>
			</el-form-item>
		</el-form>
	</PageContainer>
</template>

<style scoped></style>
